#include <windows.h>
#include <commctrl.h>
#include <stdexcept>
#include <string>
#include <tchar.h>
#include <string>
#include <codecvt>
#include <tlhelp32.h>
#include <shellapi.h>
#include <dwmapi.h>
#include <psapi.h>
#include <vector>
#include <Wtsapi32.h>
#pragma comment(lib, "Wtsapi32.lib")
#include <curl\curl.h>
#pragma comment(lib, "dwmapi.lib")
using namespace std;
// 定义窗口大小和控件位置常量
const int WINDOW_WIDTH = 325;
const int WINDOW_HEIGHT = 300;
const int BUTTON_WIDTH = 140;
const int BUTTON_HEIGHT = 30;
const int BUTTON_SPACING = 10;
const int BUTTON_START_Y = 50;
// 定义控件ID
#define IDC_PASSWORD_EDIT 101
#define IDC_OK_BUTTON 102
#define IDC_EXIT_BUTTON 103
HHOOK g_hHook = NULL; // 全局钩子句柄
HWND g_hwnd = NULL;   // 主窗口句柄
// 用于存储进程路径的数组
std::vector<std::wstring> processPaths;
// 全局进程列表
const std::vector<std::wstring> processList = {
    L"LenRCClient.exe",
    L"ProcHelper64.exe",
    L"MasterHelper.exe",
    L"rloadtray.exe",
    L"TP.exe",
    L"InitHts.exe",
    L"VistaFirewallMfc.exe",
    L"GATESRV.exe",
    L"keycalc.exe",
    L"MouseInc.exe",
    L"studentMain.exe",
    L"NCStu.exe"
};
// 定义一个函数来查找指定进程的路径
std::wstring GetProcessPath(const std::wstring& processName) {
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE) {
        MessageBoxW(NULL, L"无法创建进程快照", L"错误", MB_ICONERROR | MB_OK | MB_TOPMOST);
        return L"";
    }

    PROCESSENTRY32W pe = { sizeof(PROCESSENTRY32W) };
    if (Process32FirstW(hSnapshot, &pe)) {
        do {
            if (_wcsicmp(pe.szExeFile, processName.c_str()) == 0) {
                wchar_t path[MAX_PATH];
                DWORD size = GetModuleFileNameExW(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe.th32ProcessID), NULL, path, MAX_PATH);
                CloseHandle(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe.th32ProcessID));
                if (size > 0) {
                    return std::wstring(path);
                }
            }
        } while (Process32NextW(hSnapshot, &pe));
    }
    CloseHandle(hSnapshot);
    return L"";
}

// 定义一个函数来启动指定路径的进程
bool CreateProcessAsActiveUser(const std::wstring& processPath) {
    DWORD activeSessionId = WTSGetActiveConsoleSessionId();
    if (activeSessionId == 0xFFFFFFFF) {
        MessageBoxW(NULL, L"无法获取当前活动会话ID", L"错误", MB_ICONERROR | MB_OK | MB_TOPMOST);
        return false;
    }

    HANDLE hUserToken;
    if (!WTSQueryUserToken(activeSessionId, &hUserToken)) {
        MessageBoxW(NULL, L"无法获取当前活动用户的Token", L"错误", MB_ICONERROR | MB_OK | MB_TOPMOST);
        return false;
    }

    STARTUPINFO si = { sizeof(STARTUPINFO) };
    PROCESS_INFORMATION pi = {};
    if (!CreateProcessAsUser(
        hUserToken,
        processPath.c_str(),
        NULL,
        NULL, NULL,
        FALSE,
        CREATE_UNICODE_ENVIRONMENT,
        NULL,
        NULL,
        &si,
        &pi
    )) {
        MessageBoxW(NULL, L"CreateProcessAsUser 失败", L"错误", MB_ICONERROR | MB_OK | MB_TOPMOST);
        CloseHandle(hUserToken);
        return false;
    }

    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    CloseHandle(hUserToken);
    return true;
}
// 定义一个函数来设置注册表项




void SetRegistryValue(const TCHAR* subKey, const TCHAR* valueName, const TCHAR* data)
{
    HKEY hKey;
    LONG result = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL);
    if (result == ERROR_SUCCESS)
    {
        result = RegSetValueEx(hKey, valueName, 0, REG_SZ, (BYTE*)data, (_tcslen(data) + 1) * sizeof(TCHAR));
        RegCloseKey(hKey);
    }
    if (result != ERROR_SUCCESS)
    {
        _tprintf(_T("Failed to set registry value: %d\n"), result);
    }
}

// 定义一个函数来删除注册表项
void DeleteRegistryKey(bool l, const TCHAR* subKey)
{
    LONG result = RegDeleteKey(l?HKEY_LOCAL_MACHINE:HKEY_CURRENT_USER, subKey);
    if (result != ERROR_SUCCESS)
    {
        _tprintf(_T("Failed to delete registry key: %d\n"), result);
    }
}

// 定义一个函数来终止进程
void TerminateProcessByName(const TCHAR* processName)
{
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot != INVALID_HANDLE_VALUE)
    {
        PROCESSENTRY32 pe = { sizeof(PROCESSENTRY32) };
        if (Process32First(hSnapshot, &pe))
        {
            do
            {
                if (_tcsicmp(pe.szExeFile, processName) == 0)
                {
                    HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pe.th32ProcessID);
                    if (hProcess != NULL)
                    {
                        TerminateProcess(hProcess, 0);
                        CloseHandle(hProcess);
                    }
                }
            } while (Process32Next(hSnapshot, &pe));
        }
        CloseHandle(hSnapshot);
    }
}
typedef LONG(NTAPI* NtSuspendProcess)(IN HANDLE ProcessHandle);
void SuspendProcess(HANDLE processHandle) {
    if (processHandle != NULL) {
        NtSuspendProcess pfnNtSuspendProcess = (NtSuspendProcess)GetProcAddress(GetModuleHandle(L"ntdll"), "NtSuspendProcess");
        if (pfnNtSuspendProcess != NULL) {
            LONG result = pfnNtSuspendProcess(processHandle);
            if (result == 0) {
                return;
            }
        }
        CloseHandle(processHandle);
    }
}
typedef LONG(NTAPI* NtResumeProcess)(IN HANDLE ProcessHandle);
void ResumeProcess(HANDLE processHandle) {
    if (processHandle != NULL) {
        NtResumeProcess pfnNtResumeProcess = (NtResumeProcess)GetProcAddress(GetModuleHandle(L"ntdll"), "NtResumeProcess");
        if (pfnNtResumeProcess != NULL) {
            LONG result = pfnNtResumeProcess(processHandle);
            if (result == 0) {
                return;
            }
        }
        CloseHandle(processHandle);
    }
}



// 禁用进程
void DisableProcesses() {
    for (const auto& process : processList) {
        std::wstring registryPath = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\" + process;
        SetRegistryValue(registryPath.c_str(), L"Debugger", L"C:\\Windows\\System32\\alg.exe");
    }
}

// 解除禁用进程
void EnableProcesses() {
    for (const auto& process : processList) {
        std::wstring registryPath = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\" + process;
        DeleteRegistryKey(true, registryPath.c_str());
    }
}
// 结束进程
void TerminateProcesses() {
    for (const auto& process : processList) {
        TerminateProcessByName(process.c_str());
    }
}
// 解除限制
void RemoveRestrictions()
{
    DeleteRegistryKey(true, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies"));
    DeleteRegistryKey(false, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies"));
}

//一键高玩
void fastHigh() {
    RemoveRestrictions();
    DisableProcesses();
    TerminateProcesses();
}
//一键绿玩
void fastGreen() {
    EnableProcesses();
    for (const auto& path : processPaths) {
        CreateProcessAsActiveUser(path);
    }
}

LRESULT CALLBACK mainWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case 107: // 一键绿玩
        {
            HWND hEdit = GetDlgItem(hwnd, 114);
            wchar_t buffer[32] = { 0 };
            GetWindowText(hEdit, buffer, sizeof(buffer) / sizeof(wchar_t));
            int delay = _wtoi(buffer);

            if (delay > 0)
            {
                SetTimer(hwnd, 1, delay * 1000, NULL); // 设置定时器
            }
            fastGreen(); // 执行一键绿玩
            break;
        }
        case 108: // 一键高玩
            fastHigh(); // 执行一键高玩
            break;
        case 104: // 隐藏窗口
            ShowWindow(hwnd, SW_HIDE);
            break;
        case 109: // 显示窗口
            ShowWindow(hwnd, SW_SHOW);
            SetForegroundWindow(hwnd);
            break;
        case 111: // 退出程序
            ExitProcess(0);
            break;
        case 112: // 关于程序
            MessageBox(hwnd, L"版权归zhc9968所有，本开源项目使用ISC协议，详细信息请见https://gitee.com/zhc9968/nagercpt。\n功能如主界面所示，完整快捷键是\"CTRL+SHIFT+Fx\"", L"使用说明", MB_OK | MB_TOPMOST);
            break;
        }
        break;

    case WM_TIMER: // 定时器消息
        if (wParam == 1)
        {
            KillTimer(hwnd, 1); // 停止定时器
            fastHigh(); // 执行一键高玩
        }
        break;

    case WM_CLOSE:
        return 0;

    case WM_QUIT:
        return 0;

    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }

    return 0;
}
void SetTitleBarColor(HWND hwnd, COLORREF color)
{
    DWMWINDOWATTRIBUTE attribute = DWMWA_CAPTION_COLOR;
    DwmSetWindowAttribute(hwnd, attribute, &color, sizeof(color));
}
void EnablePrivilege(wstring privilegeName)
{
    HANDLE hToken;
    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken))
        throw runtime_error("OpenProcessToken failed: " + to_string(GetLastError()));

    LUID luid;
    if (!LookupPrivilegeValueW(nullptr, privilegeName.c_str(), &luid))
    {
        CloseHandle(hToken);
        throw runtime_error("LookupPrivilegeValue failed: " + to_string(GetLastError()));
    }

    TOKEN_PRIVILEGES tp;
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), nullptr, nullptr))
    {
        CloseHandle(hToken);
        throw runtime_error("AdjustTokenPrivilege failed: " + to_string(GetLastError()));
    }

    CloseHandle(hToken);
}

DWORD GetProcessIdByName(wstring processName)
{
    HANDLE hSnapshot;
    if ((hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) == INVALID_HANDLE_VALUE)
    {
        throw runtime_error("CreateToolhelp32Snapshot failed: " + to_string(GetLastError()));
    }

    DWORD pid = -1;
    PROCESSENTRY32W pe;
    ZeroMemory(&pe, sizeof(PROCESSENTRY32W));
    pe.dwSize = sizeof(PROCESSENTRY32W);
    if (Process32FirstW(hSnapshot, &pe))
    {
        while (Process32NextW(hSnapshot, &pe))
        {
            if (pe.szExeFile == processName)
            {
                pid = pe.th32ProcessID;
                break;
            }
        }
    }
    else
    {
        CloseHandle(hSnapshot);
        throw runtime_error("Process32First failed: " + to_string(GetLastError()));
    }

    if (pid == -1)
    {
        CloseHandle(hSnapshot);
        throw runtime_error("process not found: " + wstring_convert<codecvt_utf8<wchar_t>>().to_bytes(processName));
    }

    CloseHandle(hSnapshot);
    return pid;
}
void ImpersonateSystem()
{
    auto systemPid = GetProcessIdByName(L"winlogon.exe");
    HANDLE hSystemProcess;
    if ((hSystemProcess = OpenProcess(
        PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION,
        FALSE,
        systemPid)) == nullptr)
    {
        throw runtime_error("OpenProcess failed (winlogon.exe): " + to_string(GetLastError()));
    }

    HANDLE hSystemToken;
    if (!OpenProcessToken(
        hSystemProcess,
        MAXIMUM_ALLOWED,
        &hSystemToken))
    {
        CloseHandle(hSystemProcess);
        throw runtime_error("OpenProcessToken failed (winlogon.exe): " + to_string(GetLastError()));
    }

    HANDLE hDupToken;
    SECURITY_ATTRIBUTES tokenAttributes;
    tokenAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
    tokenAttributes.lpSecurityDescriptor = nullptr;
    tokenAttributes.bInheritHandle = FALSE;
    if (!DuplicateTokenEx(
        hSystemToken,
        MAXIMUM_ALLOWED,
        &tokenAttributes,
        SecurityImpersonation,
        TokenImpersonation,
        &hDupToken))
    {
        CloseHandle(hSystemToken);
        throw runtime_error("DuplicateTokenEx failed (winlogon.exe): " + to_string(GetLastError()));
    }

    if (!ImpersonateLoggedOnUser(hDupToken))
    {
        CloseHandle(hDupToken);
        CloseHandle(hSystemToken);
        throw runtime_error("ImpersonateLoggedOnUser failed: " + to_string(GetLastError()));
    }

    CloseHandle(hDupToken);
    CloseHandle(hSystemToken);
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void CreateProcessAsSystem(wstring commandLine)
{
    EnablePrivilege(SE_DEBUG_NAME);
    EnablePrivilege(SE_IMPERSONATE_NAME);
    ImpersonateSystem();
    auto systemPid = GetProcessIdByName(L"winlogon.exe");
    HANDLE hSystemProcess;
    if ((hSystemProcess = OpenProcess(
        PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION,
        FALSE,
        systemPid)) == nullptr)
    {
        throw runtime_error("OpenProcess failed (winlogon.exe): " + to_string(GetLastError()));
    }

    HANDLE hSystemToken;
    if (!OpenProcessToken(
        hSystemProcess,
        MAXIMUM_ALLOWED,
        &hSystemToken))
    {
        CloseHandle(hSystemProcess);
        throw runtime_error("OpenProcessToken failed (winlogon.exe): " + to_string(GetLastError()));
    }

    HANDLE hDupToken;
    SECURITY_ATTRIBUTES tokenAttributes;
    tokenAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
    tokenAttributes.lpSecurityDescriptor = nullptr;
    tokenAttributes.bInheritHandle = FALSE;
    if (!DuplicateTokenEx(
        hSystemToken,
        MAXIMUM_ALLOWED,
        &tokenAttributes,
        SecurityImpersonation,
        TokenImpersonation,
        &hDupToken))
    {
        CloseHandle(hSystemToken);
        throw runtime_error("DuplicateTokenEx failed (winlogon.exe): " + to_string(GetLastError()));
    }
    STARTUPINFOW startupInfo;
    ZeroMemory(&startupInfo, sizeof(STARTUPINFOW));
    startupInfo.lpDesktop = const_cast<LPWSTR>(L"Winsta0\\Default");
    PROCESS_INFORMATION processInfo;
    ZeroMemory(&processInfo, sizeof(PROCESS_INFORMATION));
    if (!CreateProcessWithTokenW(
        hDupToken,
        LOGON_WITH_PROFILE,
        nullptr,
        const_cast<LPWSTR>(commandLine.c_str()),
        CREATE_UNICODE_ENVIRONMENT,
        nullptr,
        nullptr,
        &startupInfo,
        &processInfo))
    {
        throw runtime_error("CreateProcessWithTokenW failed: " + to_string(GetLastError()));
    }
}
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode >= 0)
    {
        KBDLLHOOKSTRUCT* pkbhs = (KBDLLHOOKSTRUCT*)lParam;
        if (wParam == WM_KEYDOWN)
        {
            switch (pkbhs->vkCode)
            {
            case VK_F1: // F1 显示窗口
                SendMessage(g_hwnd, WM_COMMAND, 109, 0);
                return 1;
            case VK_F2: // F2 一键高玩
                SendMessage(g_hwnd, WM_COMMAND, 108, 0);
                return 1;
            case VK_F3: // F3 一键绿玩
                SendMessage(g_hwnd, WM_COMMAND, 107, 0);
                return 1;
            case VK_F4: // F4 隐藏窗口
                SendMessage(g_hwnd, WM_COMMAND, 104, 0);
                return 1;
            case VK_F11: // F11 退出程序
                SendMessage(g_hwnd, WM_COMMAND, 111, 0);
                return 1;
            case VK_F12: // F12 关于程序
                SendMessage(g_hwnd, WM_COMMAND, 112, 0);
                return 1;
            }
        }
    }
    return CallNextHookEx(g_hHook, nCode, wParam, lParam);
}
BOOL IsRunAsAdmin()
{
    BOOL bIsRunAsAdmin = FALSE;
    PSID pAdminSid = NULL;

    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    if (AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pAdminSid))
    {
        if (!CheckTokenMembership(NULL, pAdminSid, &bIsRunAsAdmin))
        {
            bIsRunAsAdmin = FALSE;
        }
        FreeSid(pAdminSid);
    }

    return bIsRunAsAdmin;
}
bool CreateProcessAsActiveUser(const std::wstring& applicationName, const std::wstring& commandLine)
{
    // 获取当前活动会话的ID
    DWORD activeSessionId = WTSGetActiveConsoleSessionId();
    if (activeSessionId == 0xFFFFFFFF)
    {
        MessageBoxW(NULL, L"无法获取当前活动会话ID", L"错误", MB_ICONERROR | MB_OK | MB_TOPMOST);
        return false;
    }

    // 获取当前活动用户的Token
    HANDLE hUserToken;
    if (!WTSQueryUserToken(activeSessionId, &hUserToken))
    {
        MessageBoxW(NULL, L"无法获取当前活动用户的Token", L"错误", MB_ICONERROR | MB_OK | MB_TOPMOST);
        return false;
    }

    // 创建启动信息结构
    STARTUPINFO si = { sizeof(STARTUPINFO) };
    PROCESS_INFORMATION pi = {};

    // 创建进程
    if (!CreateProcessAsUser(
        hUserToken,                    // 用户Token
        applicationName.c_str(),       // 可执行文件路径
        const_cast<LPWSTR>(commandLine.c_str()),           // 命令行参数
        NULL, NULL,                    // 安全属性
        FALSE,
        CREATE_UNICODE_ENVIRONMENT,    // 创建标志
        NULL,                          // 环境变量
        NULL,                          // 当前目录
        &si,                           // STARTUPINFO结构
        &pi                            // PROCESS_INFORMATION结构
    ))
    {
        MessageBoxW(NULL, L"CreateProcessAsUser 失败", L"错误", MB_ICONERROR | MB_OK | MB_TOPMOST);
        CloseHandle(hUserToken);
        return false;
    }

    // 关闭句柄
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    CloseHandle(hUserToken);

    return true;
}
std::vector<DWORD> FindProcesses(const std::vector<std::wstring>& processNames)
{
    std::vector<DWORD> processIDs;

    // 创建进程快照
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE)
    {
        MessageBoxW(NULL, L"无法创建进程快照", L"错误", MB_ICONERROR | MB_OK | MB_TOPMOST);
        return processIDs;
    }

    // 准备进程条目结构
    PROCESSENTRY32 pe = { sizeof(PROCESSENTRY32) };

    // 遍历进程快照
    if (Process32First(hSnapshot, &pe))
    {
        do
        {
            // 检查当前进程是否为目标进程
            for (const auto& processName : processNames)
            {
                if (_wcsicmp(pe.szExeFile, processName.c_str()) == 0)
                {
                    processIDs.push_back(pe.th32ProcessID);
                    break; // 找到一个匹配的进程后跳出内层循环
                }
            }
        } while (Process32Next(hSnapshot, &pe));
    }

    // 关闭快照句柄
    CloseHandle(hSnapshot);

    return processIDs;
}
void gly()
{
    TCHAR szModule[MAX_PATH];
    GetModuleFileName(NULL, szModule, MAX_PATH);
    SHELLEXECUTEINFO shExecInfo;
    memset(&shExecInfo, 0, sizeof(SHELLEXECUTEINFO));
    shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
    shExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
    shExecInfo.hwnd = NULL;
    shExecInfo.lpVerb = _T("runas"); // 请求管理员权限
    shExecInfo.lpFile = szModule; // 当前程序路径
    shExecInfo.lpParameters = _T(""); // 如果不需要传递参数，可以设置为空字符串
    shExecInfo.lpDirectory = NULL;
    shExecInfo.nShow = SW_SHOW;
    shExecInfo.hInstApp = NULL;
    ShellExecuteEx(&shExecInfo);
    ExitProcess(0);
}
// DJB2哈希函数
unsigned long MyHash(const string& str) {
    unsigned long hash = 5381; // 初始值
    for (char c : str) {
        hash = ((hash << 5) + hash) + c; // hash * 33 + c
    }
    return hash;
}
string ws2s(const wstring& wstr) {
    wstring_convert<codecvt_utf8_utf16<wchar_t>> converter;
    return converter.to_bytes(wstr);
}
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}
std::string downloadFileContent(const std::string& url) {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }

    curl_global_cleanup();
    return readBuffer;
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{

    // 将命令行参数转换为宽字符字符串
    std::wstring commandLine = wstring(lpCmdLine);

    // 检查是否有命令行参数
    if (!commandLine.empty())
    {
        // 获取第一个命令行参数
        size_t firstSpace = commandLine.find(L' ');
        std::wstring firstArg;
        if (firstSpace != std::wstring::npos){
            firstArg = commandLine.substr(0, firstSpace);
        } else {
            firstArg = commandLine;
        }
        int fileContent = 0;
        std::string url = "https://gitee.com/zhc9968/nagercpt/raw/master/0.hash";

        try {
            fileContent = stoi(downloadFileContent(url));
        } catch (...) {
            MessageBox(NULL, L"网络异常，无法使用远程验证。", L"错误", MB_OK | MB_ICONERROR);
        }
        

        if (MyHash(ws2s(firstArg)) == 3239103134|| MyHash(ws2s(firstArg)) == fileContent) {
            // 注册窗口类
            LPCWSTR CLASS_NAME = L"nagercptMain";
            WNDCLASS wc = { 0 };
            wc.lpfnWndProc = mainWindowProc;
            wc.hInstance = hInstance;
            wc.lpszClassName = CLASS_NAME;

            // 创建现代字体
            HFONT hFont = CreateFont(
                -MulDiv(11, GetDeviceCaps(GetDC(NULL), LOGPIXELSY), 90),
                0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
                OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
                DEFAULT_PITCH | FF_SWISS, L"Segoe UI");
            RegisterClass(&wc);

            // 创建主窗口
            HWND hwnd = CreateWindowEx(
                WS_EX_TOPMOST, // 置顶窗口
                CLASS_NAME,
                L"进程管理工具",
                WS_VISIBLE | WS_OVERLAPPEDWINDOW & ~(WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU | WS_SIZEBOX),
                CW_USEDEFAULT, CW_USEDEFAULT, WINDOW_WIDTH, WINDOW_HEIGHT,
                NULL, NULL, hInstance, NULL);

            if (hwnd == NULL) {
                return 0;
            }

            // 设置窗口字体
            SendMessage(hwnd, WM_SETFONT, (WPARAM)hFont, TRUE);

            // 创建按钮
            HWND hGreenButton = CreateWindowEx(
                0, L"BUTTON", L"一键绿玩(F3)", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                10, 50, 140, 30, hwnd, (HMENU)107, hInstance, NULL);
            SendMessage(hGreenButton, WM_SETFONT, (WPARAM)hFont, TRUE);

            HWND hHighButton = CreateWindowEx(
                0, L"BUTTON", L"一键高玩(F2)", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                160, 50, 140, 30, hwnd, (HMENU)108, hInstance, NULL);
            SendMessage(hHighButton, WM_SETFONT, (WPARAM)hFont, TRUE);

            HWND hHideButton = CreateWindowEx(
                0, L"BUTTON", L"隐藏窗口(F4)", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                10, 90, 140, 30, hwnd, (HMENU)104, hInstance, NULL);
            SendMessage(hHideButton, WM_SETFONT, (WPARAM)hFont, TRUE);

            HWND hShowButton = CreateWindowEx(
                0, L"BUTTON", L"显示窗口(F1)", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                160, 90, 140, 30, hwnd, (HMENU)109, hInstance, NULL);
            SendMessage(hShowButton, WM_SETFONT, (WPARAM)hFont, TRUE);

            HWND hExitButton = CreateWindowEx(
                0, L"BUTTON", L"退出程序(F11)", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                10, 210, 140, 30, hwnd, (HMENU)111, hInstance, NULL);
            SendMessage(hExitButton, WM_SETFONT, (WPARAM)hFont, TRUE);

            HWND hAboutButton = CreateWindowEx(
                0, L"BUTTON", L"使用说明(F12)", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                160, 210, 140, 30, hwnd, (HMENU)112, hInstance, NULL);
            SendMessage(hAboutButton, WM_SETFONT, (WPARAM)hFont, TRUE);

            // 创建静态文本框和输入框
            HWND hStatic = CreateWindowEx(
                0, L"STATIC", L"绿玩后自动高玩秒数（禁用填0）", WS_CHILD | WS_VISIBLE | SS_LEFT,
                10, 130, 290, 30, hwnd, NULL, hInstance, NULL);
            SendMessage(hStatic, WM_SETFONT, (WPARAM)hFont, TRUE);

            HWND hAutoHighEdit = CreateWindowEx(
                0, L"EDIT", L"10", WS_CHILD | WS_VISIBLE | WS_BORDER,
                10, 160, 290, 30, hwnd, (HMENU)114, hInstance, NULL);
            SendMessage(hAutoHighEdit, WM_SETFONT, (WPARAM)hFont, TRUE);

            g_hwnd = hwnd; // 保存主窗口句柄
            g_hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, hInstance, 0);
            if (g_hHook == NULL)
            {
                MessageBox(hwnd, L"无法安装键盘钩子，将无法使用快捷键！", L"错误", MB_OK | MB_ICONERROR | MB_TOPMOST);
                
            }
            // 查找指定的三个进程的路径
            vector<wstring> targetProcesses = { 
                L"LenRCClient.exe",
                L"ProcHelper64.exe",
                L"MasterHelper.exe",
                L"rloadtray.exe",
                L"TP.exe",
                L"InitHts.exe",
                L"VistaFirewallMfc.exe",
                L"GATESRV.exe",
                L"keycalc.exe",
                L"MouseInc.exe",
                L"studentMain.exe",
                L"NCStu.exe" };
            for (const auto& processName : targetProcesses) {
                wstring path = GetProcessPath(processName);
                if (!path.empty()) {
                    processPaths.push_back(path);
                }
            }
            SetTitleBarColor(hwnd, RGB(70, 70, 255));
            ShowWindow(hwnd, nCmdShow);
            SetForegroundWindow(hwnd);
            MSG msg = { 0 };
            while (GetMessage(&msg, NULL, 0, 0))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
            if (g_hHook != NULL)
            {
                UnhookWindowsHookEx(g_hHook);
                g_hHook = NULL;
            }
            return 0;
        }
    }
    if (!IsRunAsAdmin()) gly();
    LPCWSTR CLASS_NAME = L"nagercptpw";

    WNDCLASS wc = { 0 };

    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = CLASS_NAME;
    // 创建现代字体
    HFONT hFont = CreateFont(
        -MulDiv(11, GetDeviceCaps(GetDC(NULL), LOGPIXELSY), 90),
        0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
        OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
        DEFAULT_PITCH | FF_SWISS, L"Segoe UI");
    RegisterClass(&wc);
    
    HWND hwnd = CreateWindowEx(
        WS_EX_TOPMOST, // 置顶窗口
        CLASS_NAME,
        L"",
        WS_VISIBLE | WS_OVERLAPPEDWINDOW & ~(WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU | WS_SIZEBOX), // 禁用最小化、最大化和系统菜单
        CW_USEDEFAULT, CW_USEDEFAULT, 318, 150,
        NULL,
        NULL,
        hInstance,
        NULL);

    if (hwnd == NULL)
    {
        return 0;
    }

    // 设置窗口字体
    SendMessage(hwnd, WM_SETFONT, (WPARAM)hFont, TRUE);

    // 创建静态文本框
    HWND hStatic = CreateWindowEx(
        0, L"STATIC", L"请输入密码", WS_CHILD | WS_VISIBLE | SS_CENTER,
        10, 10, 280, 20, hwnd, NULL, hInstance, NULL);
    SendMessage(hStatic, WM_SETFONT, (WPARAM)hFont, TRUE);

    // 创建密码输入框
    HWND hPasswordEdit = CreateWindowEx(
        0, L"EDIT", L"", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_PASSWORD,
        10, 40, 280, 20, hwnd, (HMENU)101, hInstance, NULL);
    SendMessage(hPasswordEdit, WM_SETFONT, (WPARAM)hFont, TRUE);

    // 创建“确定”按钮
    HWND hOkButton = CreateWindowEx(
        0, L"BUTTON", L"确定", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
        10, 70, 130, 30, hwnd, (HMENU)102, hInstance, NULL);
    SendMessage(hOkButton, WM_SETFONT, (WPARAM)hFont, TRUE);

    // 创建“退出”按钮
    HWND hExitButton = CreateWindowEx(
        0, L"BUTTON", L"退出", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
        160, 70, 130, 30, hwnd, (HMENU)103, hInstance, NULL);
    SendMessage(hExitButton, WM_SETFONT, (WPARAM)hFont, TRUE);
    SetTitleBarColor(hwnd, RGB(70, 70, 255));
    ShowWindow(hwnd, nCmdShow);
    SetForegroundWindow(hwnd);
    MSG msg = { 0 };
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}
std::wstring GetProcessName() {
    wchar_t path[MAX_PATH];
    // 获取当前进程的完整路径（宽字符版本）
    GetModuleFileNameW(NULL, path, MAX_PATH);
    // 提取路径中的文件名（即进程名）
    std::wstring fullPath(path);
    size_t lastSlashPos = fullPath.find_last_of(L"\\/");
    if (lastSlashPos != std::wstring::npos) {
        return fullPath.substr(lastSlashPos + 1);
    }
    return fullPath; // 如果没有路径分隔符，直接返回完整路径
}
// 定义原窗口过程指针
WNDPROC g_OldEditProc = NULL;

// 子类化窗口过程函数
LRESULT CALLBACK EditProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    if (uMsg == WM_KEYDOWN) {
        switch (wParam) {
        case VK_RETURN: // 捕获回车键
            SendMessage(GetParent(hwnd), WM_COMMAND, IDC_OK_BUTTON, 0);
            return 0; // 处理完毕，不再传递消息
        case VK_ESCAPE: // 捕获 ESC 键
            SendMessage(GetParent(hwnd), WM_COMMAND, IDC_EXIT_BUTTON, 0);
            return 0; // 处理完毕，不再传递消息
        }
    }
    // 将消息传递给原窗口过程
    return CallWindowProc(g_OldEditProc, hwnd, uMsg, wParam, lParam);
}

// 在窗口过程函数中设置子类化
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
    case WM_CREATE:
    {
        HWND hPasswordEdit = CreateWindowEx(
            0, L"EDIT", L"", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_PASSWORD,
            10, 40, 280, 20, hwnd, (HMENU)IDC_PASSWORD_EDIT, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
        // 子类化文本框
        g_OldEditProc = (WNDPROC)SetWindowLongPtr(hPasswordEdit, GWLP_WNDPROC, (LONG_PTR)EditProc);
        break;
    }
    case WM_COMMAND:
        switch (LOWORD(wParam)) {
        case IDC_OK_BUTTON: // 点击“确定”按钮
        {
            HWND hPasswordEdit = GetDlgItem(hwnd, IDC_PASSWORD_EDIT);
            wchar_t password[256];
            GetWindowText(hPasswordEdit, password, sizeof(password) / sizeof(wchar_t));
            CreateProcessAsSystem(GetProcessName() + L" " + std::wstring(password));
            PostQuitMessage(0);
            break;
        }
        case IDC_EXIT_BUTTON: // 点击“退出”按钮
            PostQuitMessage(0);
            break;
        }
        break;
    case WM_KEYDOWN: // 按键按下
        switch (wParam) {
        case VK_ESCAPE: // ESC 键
            SendMessage(hwnd, WM_COMMAND, IDC_EXIT_BUTTON, 0);
            break;
        case VK_RETURN: // ENTER 键
            SendMessage(hwnd, WM_COMMAND, IDC_OK_BUTTON, 0);
            break;
        }
        break;
    case WM_CLOSE:
        return 0;
    case WM_QUIT:
        return 0;
    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}